package example.TCPTest;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class SimpleTcpServer {
    public static void main(String[] args) {
        // 使用 try-with-resources 自动关闭资源
        try (ServerSocket serverSocket = new ServerSocket(8888)) {
            System.out.println("服务器启动，监听端口 8888...");
            
            // 持续接受客户端连接
            while (true) {
                // 等待客户端连接（阻塞方法）
                Socket clientSocket = serverSocket.accept();
                System.out.println("客户端连接来自: " + clientSocket.getInetAddress());
                
                // 为每个客户端创建新线程处理
                new ClientHandler(clientSocket).start();
            }
            
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

// 客户端处理线程
class ClientHandler extends Thread {
    private Socket clientSocket;
    
    public ClientHandler(Socket socket) {
        this.clientSocket = socket;
    }
    
    @Override
    public void run() {
        try (BufferedReader in = new BufferedReader(
                new InputStreamReader(clientSocket.getInputStream()));
             PrintWriter out = new PrintWriter(
                clientSocket.getOutputStream(), true)) {
            
            String inputLine;
            // 读取客户端发送的数据
            while ((inputLine = in.readLine()) != null) {
                System.out.println("收到客户端消息: " + inputLine);
                
                // 回复客户端
                String response = "服务器响应: " + inputLine.toUpperCase();
                out.println(response);
                
                // 如果客户端发送 "bye"，结束对话
                if ("bye".equalsIgnoreCase(inputLine)) {
                    out.println("连接关闭");
                    break;
                }
            }
            
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                clientSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println(clientSocket + "结束~~~~");
    }
}